package com.bf.electroplating.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bf.electroplating.pojo.dto.RainfallMonthlyDataRequestDTO;
import com.bf.electroplating.pojo.dto.RainfallMonthlyDataResponseDTO;
import com.bf.electroplating.pojo.entity.RainfallOutletSite;
import com.bf.electroplating.pojo.entity.SiteMonthlyStatistics;
import com.bf.electroplating.service.IRainfallMonthlyDataSyncService;
import com.bf.electroplating.service.IRainfallOutletSiteService;
import com.bf.electroplating.service.ISiteMonthlyStatisticsService;
import com.bf.electroplating.util.SignUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 雨水月度数据同步服务实现类
 *
 * @author system
 * @since 2025-01-11
 */
@Slf4j
@Service
public class RainfallMonthlyDataSyncServiceImpl implements IRainfallMonthlyDataSyncService {

    @Autowired
    private IRainfallOutletSiteService rainfallOutletSiteService;

    @Autowired
    private ISiteMonthlyStatisticsService siteMonthlyStatisticsService;

    @Value("${company.api.baseUrl}")
    private String apiBaseUrl;

    @Value("${company.api.secret}")
    private String apiSecret;

    private final RestTemplate restTemplate = new RestTemplate();

    @Override
    public void syncAllRainfallMonthlyData() {
        log.info("开始同步所有站点的雨水月度数据");
        
        try {
            // 获取所有站点
            List<RainfallOutletSite> sites = rainfallOutletSiteService.list();
            
            if (sites.isEmpty()) {
                log.warn("没有找到雨排口站点，请检查站点列表同步是否成功");
                return;
            }

            // 为每个站点同步月度数据
            for (RainfallOutletSite site : sites) {
                try {
                    syncRainfallMonthlyDataBySiteId(site.getSiteId());
                } catch (Exception e) {
                    log.error("同步站点 {} 的雨水月度数据失败", site.getSiteName(), e);
                }
            }

            log.info("所有站点雨水月度数据同步完成");
        } catch (Exception e) {
            log.error("同步所有站点雨水月度数据失败", e);
        }
    }

    @Override
    public void syncRainfallMonthlyDataBySiteId(Integer siteId) {
        log.info("开始同步站点 {} 的雨水月度数据", siteId);
        
        try {
            // 获取最近30天的数据
            LocalDateTime endTime = LocalDateTime.now();
            LocalDateTime beginTime = endTime.minusDays(30);
            
            String beginTimeStr = beginTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            String endTimeStr = endTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            
            syncRainfallMonthlyDataByTimeRange(siteId, beginTimeStr, endTimeStr);
            
            log.info("站点 {} 的雨水月度数据同步完成", siteId);
        } catch (Exception e) {
            log.error("同步站点 {} 的雨水月度数据失败", siteId, e);
        }
    }

    @Override
    public void syncRainfallMonthlyDataByTimeRange(Integer siteId, String beginTime, String endTime) {
        log.info("开始同步站点 {} 在 {} 到 {} 时间范围内的雨水月度数据", siteId, beginTime, endTime);
        
        try {
            // 构建请求参数
            RainfallMonthlyDataRequestDTO requestDTO = new RainfallMonthlyDataRequestDTO();
            requestDTO.setSiteId(siteId);
            requestDTO.setBeginTime(beginTime);
            requestDTO.setEndTime(endTime);
            requestDTO.setPage(1);
            requestDTO.setPageSize(100);

            // 调用外部API
            String response = callRainfallMonthlyDataAPI(requestDTO);
            
            // 解析响应数据
            RainfallMonthlyDataResponseDTO responseDTO = JSON.parseObject(response, RainfallMonthlyDataResponseDTO.class);
            
            if (responseDTO == null || !responseDTO.getSuccess() || responseDTO.getList() == null) {
                log.warn("站点 {} 的雨水月度数据API返回失败或为空", siteId);
                return;
            }

            // 保存数据到数据库
            saveRainfallMonthlyData(siteId, responseDTO.getList());
            
            log.info("站点 {} 在指定时间范围内的雨水月度数据同步完成，共处理 {} 条数据", 
                    siteId, responseDTO.getList().size());
        } catch (Exception e) {
            log.error("同步站点 {} 在指定时间范围内的雨水月度数据失败", siteId, e);
        }
    }

    @Override
    public void syncRainfallMonthlyDataWithPagination(Integer siteId, String beginTime, String endTime, Integer page, Integer pageSize) {
        log.info("开始同步站点 {} 在 {} 到 {} 时间范围内的雨水月度数据，页码: {}, 每页大小: {}", 
                siteId, beginTime, endTime, page, pageSize);
        
        try {
            // 构建请求参数
            RainfallMonthlyDataRequestDTO requestDTO = new RainfallMonthlyDataRequestDTO();
            requestDTO.setSiteId(siteId);
            requestDTO.setBeginTime(beginTime);
            requestDTO.setEndTime(endTime);
            requestDTO.setPage(page);
            requestDTO.setPageSize(pageSize);

            // 调用外部API
            String response = callRainfallMonthlyDataAPI(requestDTO);
            
            // 解析响应数据
            RainfallMonthlyDataResponseDTO responseDTO = JSON.parseObject(response, RainfallMonthlyDataResponseDTO.class);
            
            if (responseDTO == null || !responseDTO.getSuccess() || responseDTO.getList() == null) {
                log.warn("站点 {} 的雨水月度数据API返回失败或为空", siteId);
                return;
            }

            // 保存数据到数据库
            saveRainfallMonthlyData(siteId, responseDTO.getList());
            
            log.info("站点 {} 在指定时间范围内的雨水月度数据同步完成，共处理 {} 条数据", 
                    siteId, responseDTO.getList().size());
        } catch (Exception e) {
            log.error("同步站点 {} 在指定时间范围内的雨水月度数据失败", siteId, e);
        }
    }

    /**
     * 调用雨水月度数据API
     */
    private String callRainfallMonthlyDataAPI(RainfallMonthlyDataRequestDTO requestDTO) {
        try {
            String url = apiBaseUrl + "/out/site/data/month/list";
            
            // 使用签名工具类的加密方法
            String encryptedParams = SignUtil.generateParams(requestDTO);
            
            log.debug("调用雨水月度数据API: {}, 参数: {}", url, encryptedParams);
            
            // 发送POST请求
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            
            String response = restTemplate.postForObject(url, encryptedParams, String.class, headers);
            
            log.debug("雨水月度数据API响应: {}", response);
            
            return response;
        } catch (Exception e) {
            log.error("调用雨水月度数据API失败", e);
            throw new RuntimeException("调用雨水月度数据API失败: " + e.getMessage());
        }
    }

    /**
     * 保存雨水月度数据到数据库
     */
    private void saveRainfallMonthlyData(Integer siteId, List<RainfallMonthlyDataResponseDTO.RainfallMonthlyDataItemDTO> dataList) {
        try {
            // 获取站点信息
            RainfallOutletSite site = rainfallOutletSiteService.getOne(
                new LambdaQueryWrapper<RainfallOutletSite>()
                    .eq(RainfallOutletSite::getSiteId, siteId)
            );
            
            if (site == null) {
                log.warn("未找到站点ID为 {} 的站点信息", siteId);
                return;
            }

            for (RainfallMonthlyDataResponseDTO.RainfallMonthlyDataItemDTO item : dataList) {
                try {
                    // 检查是否已存在相同日期的数据
                    SiteMonthlyStatistics existingData = siteMonthlyStatisticsService.getOne(
                        new LambdaQueryWrapper<SiteMonthlyStatistics>()
                            .eq(SiteMonthlyStatistics::getSiteId, siteId)
                            .eq(SiteMonthlyStatistics::getVDate, item.getVDate())
                            .eq(SiteMonthlyStatistics::getStatType, "02") // 电导率
                    );

                    SiteMonthlyStatistics statistics = new SiteMonthlyStatistics();
                    
                    if (existingData != null) {
                        // 更新现有数据
                        statistics = existingData;
                        statistics.setUpdateTime(LocalDateTime.now());
                        statistics.setUpdateBy("system");
                    } else {
                        // 创建新数据
                        statistics.setId(UUID.randomUUID().toString().replace("-", ""));
                        statistics.setCreateTime(LocalDateTime.now());
                        statistics.setCreateBy("system");
                        statistics.setDelFlag("0");
                        statistics.setDataSource("01"); // 自动计算
                    }

                    // 设置基本信息
                    statistics.setSiteId(siteId);
                    statistics.setSiteName(item.getSiteName());
                    statistics.setVDate(item.getVDate());
                    statistics.setVMax(item.getVMax());
                    statistics.setVMin(item.getVMin());
                    statistics.setVAvg(item.getVAvg());
                    statistics.setVNum(item.getVNum());
                    statistics.setStatType("02"); // 电导率
                    statistics.setParkId("1001"); // 默认园区ID
                    statistics.setCompanyId(null); // RainfallOutletSite中没有companyId字段

                    // 保存或更新数据
                    if (existingData != null) {
                        siteMonthlyStatisticsService.updateById(statistics);
                    } else {
                        siteMonthlyStatisticsService.save(statistics);
                    }

                } catch (Exception e) {
                    log.error("保存雨水月度数据失败，站点ID: {}, 日期: {}", siteId, item.getVDate(), e);
                }
            }

            log.info("站点 {} 的雨水月度数据保存完成，共处理 {} 条数据", siteId, dataList.size());
        } catch (Exception e) {
            log.error("保存雨水月度数据失败", e);
        }
    }
}
